package com.example.springbootmybatis.controller;

import com.example.springbootmybatis.entity.*;
import com.example.springbootmybatis.mapper.BookMapper;
import com.example.springbootmybatis.service.BookService;
import com.example.springbootmybatis.service.ECharsDataService;
import com.example.springbootmybatis.util.ToolUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.util.*;

@Slf4j
@CrossOrigin
@RequestMapping("/book")
@RestController
public class BookController {

    @Autowired
    BookMapper bookMapper;

    @RequestMapping("/testException")
    public Map test() {
        Map<String, String> map = new HashMap<>();
        int i = 1;
        System.out.println(i / 0);
        return map;
    }

    @RequestMapping("/getBooksByWhere")
    public ResultMap<? extends Object> getBooksByWhere(@RequestBody BookEntity book) {
        PageHelper.startPage(book.getPageindex(), book.getPagesize());
        List<BookEntity> allBooks = bookMapper.getBooksByWhere(book);
        PageInfo<?> resultForPage = ToolUtil.getResultForPage(allBooks);
        return ToolUtil.getResult(resultForPage, "查询");
    }


    @RequestMapping("/deleteUsersByIds")
    public ResultMap<? extends Object> deleteUsersByIds(@RequestBody List<Integer> ids) {
//        int j =0;
//        System.out.println(1/j);
        int i = bookMapper.deleteUserByIDs(ids);

        return ToolUtil.getResult(i, "删除");
    }

    @RequestMapping("/updateBookByID")
    public ResultMap<? extends Object> updateBookByID(@RequestBody BookEntity entity) {
        int i = bookMapper.updateBookByID(entity);
        if (i > 0) {
            bookId = entity.getBookId();
        }
        return ToolUtil.getResult(i, "修改");
    }


    public List<BorrowBookEntity> checkBorrowBookInfoByBorrowInfo(BorrowBookEntity entity) {
        List<BorrowBookEntity> borrowBookEntities = bookMapper.checkBorrowBookInfoByBorrowInfo(entity);
        return borrowBookEntities;
    }

    @RequestMapping("/getBorrowBookInfoByID/{uid}")
    public ResultMap<? extends Object> getBorrowBookInfoByID(@PathVariable("uid") String uid) {
        List<BorrowInfo> entity = bookMapper.getBorrowBookInfoByID(Integer.parseInt(uid));
        return ToolUtil.getResult(entity, "查询");
    }


    @RequestMapping("/getBorrowBookInfoByID1/{uid}")
    public ResultMap<? extends Object> getBorrowBookInfoByID1(@PathVariable("uid") String uid) {
        List<UserEntity> entities = bookMapper.getBorrowBookInfoByID1(Integer.parseInt(uid));
        return ToolUtil.getResult(entities, "查询");
    }

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ECharsDataService eCharsDataService;

    @RequestMapping("/borrowBook")
    public ResultMap<Integer> borrowBook(@RequestBody BorrowBookEntity entity) throws ParseException {
        ResultMap<Integer> resultMap = new ResultMap<>();
        List<BorrowBookEntity> borrowBookEntities = checkBorrowBookInfoByBorrowInfo(entity);
        if (borrowBookEntities.size() > 0) {
            resultMap.setCode(-1);
            resultMap.setMsg("你已经借过此书还未归还");
        } else {
            int i = bookMapper.borrowBook(entity);
            int j = bookMapper.BorrowPlusByID(entity.getBookId());

            if (i > 0 && j > 0) {
                ToolUtil.setRedisDataLend(redisTemplate);
                eCharsDataService.setBorrowMonth();
                log.info("借书数量  "+redisTemplate.opsForValue().get(ToolUtil.DateFormat(new Date()) + "_lend"));
                resultMap.setCode(200);
                resultMap.setResult(i + j);
                resultMap.setMsg("借书成功");
            } else {
                resultMap.setCode(-1);
                resultMap.setMsg("借书失败");
            }
        }
        return resultMap;


    }

    @RequestMapping("/returningBook")
    public ResultMap<? extends Object> returningBook(@RequestBody BorrowBookEntity entity) throws ParseException {
        Integer i = bookMapper.returningBook(entity);
        Integer j = bookMapper.returnPlusByID(entity.getBookId());
        if (i > 0) {
            ToolUtil.setRedisDataBorrow(redisTemplate);
            eCharsDataService.setReturnMonth();
            log.info("还书数量  "+redisTemplate.opsForValue().get(ToolUtil.DateFormat(new Date()) + "_Borrow"));
        }
        return ToolUtil.getResult(i, "还书");
    }

    @RequestMapping("/renewBook")
    public ResultMap<? extends Object> renewBook(@RequestBody BorrowBookEntity entity) {
        Integer i = bookMapper.renewBook(entity);
        return ToolUtil.getResult(i, "续借");
    }


    @RequestMapping("/updateBookAvatar")
    public ResultMap updateBookAvatar(BookEntity entity) {
        int i = bookMapper.updateBookAvatar(entity);
        return ToolUtil.getResult(i, "图片");
    }


    private int bookId = 0;

    @RequestMapping("/addBookItem")
    public ResultMap addBookItem(@RequestBody BookEntity entity) {
        int i = bookMapper.addBook(entity);
        if (i > 0) {
            bookId = entity.getBookId();
        }
        return ToolUtil.getResult(bookId, "添加");
    }


    @Value("${upload.rootPath}")
    private String rootPath;

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile[] multipartFiles) {
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        for (MultipartFile file :
                multipartFiles) {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
            String newFileName = UUID.randomUUID().toString() + "." + suffix;
            File newFile = new File(rootPath + newFileName);
            try {
                file.transferTo(newFile);
                BookEntity entity = new BookEntity();
                entity.setBookId(bookId);
                entity.setAvatar(newFileName);
                updateBookAvatar(entity);
                return newFileName;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

        return "error";
    }

    @Autowired
    BookService bookService;

    @RequestMapping("/getBookTypes")
    public ResultMap getBookTypes() {
        List<BookTypeEntity> bookTypes = bookService.getBookTypes();
        return ToolUtil.getResult(bookTypes, "查询");
    }

}
